/*
 * @Author: Turump 
 * @Date: 2021-03-26 17:49:31 
 * @Last Modified by: Turump
 * @Last Modified time: 2021-09-17 11:13:25
 * !!!必须创建分组captureLayer
 */
import SingletonBase from "./SingleTonBase";

export default class TFrameResLoadHelper extends SingletonBase {

    /**
     * 加载获取粒子资源，可能或为空
     * @param path 相对于particle/plist下的路径,不需要加particle/plist
     * @returns 
     */
    public getParticleAsyn(bundleName:string, path: string): Promise<cc.ParticleAsset | null> {
        if (path.includes('particle/plist') == false) {
            path = 'particle/plist/' + path;
        }
        return new Promise((resolve) => {
            this.getBundleAsyn(bundleName).then((bundle: cc.AssetManager.Bundle) => {
                bundle.load(path, cc.ParticleAsset, (err: Error, particleAsset: cc.ParticleAsset) => {
                    if (err) {
                        cc.error(`TFrameResLoadHelper load particle err:${err.message}`);
                    }
                    resolve(particleAsset);
                })
            })
        })
    }

    /**
     * 加载Frame中的图片资源
     * @param path 相对于TFrameRes的路径
     * @returns 
     */
    public getSpriteFrameAsyn(bundleName: string, path: string): Promise<cc.SpriteFrame | null> {
        return new Promise((resolve) => {
            this.getBundleAsyn(bundleName).then((bundle: cc.AssetManager.Bundle) => {
                bundle.load(path, cc.SpriteFrame, (err: Error, frame: cc.SpriteFrame) => {
                    if (err) {
                        cc.error(`TFrameResLoadHelper load particle err:${err.message}`);
                    }
                    resolve(frame);
                })
            })
        })
    }

    /**
     * 根据bundle名称获取bundle对象
     * @param bundleName 
     * @returns bundle对象,失败返回null
     */
    public getBundleAsyn(bundleName: string): Promise<cc.AssetManager.Bundle> {
        return new Promise((resolve) => {
            cc.assetManager.loadBundle(bundleName, (err: Error, lbundle: cc.AssetManager.Bundle) => {
                if (err) {
                    cc.error("TF error:", err.message);
                }
                resolve(lbundle);
            })
        })
    }

    public getResAsyn<T extends cc.Asset>(bundleName, resPath, type: typeof cc.Asset): Promise<T> {
        return new Promise((resolve) => {
            this.getBundleAsyn(bundleName).then((bundle: cc.AssetManager.Bundle) => {
                if (bundle == null) {
                    resolve(null);
                    return;
                }
                bundle.load(resPath, type, (err: Error, res: T) => {
                    if (err) {
                        cc.error("TF error:", err.message);
                        resolve(null);
                        return
                    }
                    resolve(res)
                })
            })
        })
    }
}
